#include <iostream>
#include "l1ioapi.h"

//If open, bail, otherwise, open and return true;
int l1api::pipe::open(){
  if(m_is_open)
    return -1;
  m_is_open = true;
  return 0;
}
//If closed, bail, otherwise, close it :)
int l1api::pipe::close(){
  if(!m_is_open)
    return -1;
  m_is_open = false;
  return 0;
}

//If not open, bail
int l1api::pipe::write(const char * &buf, ssize_t len){
  if(!m_is_open)
    return -1;
  if(len > 4096 || len <= 0)    
    return -1;
  m_ostringstream.str(std::string());
  m_ostringstream.write(buf, len);
  return len;
}

int l1api::pipe::read(char * buf, ssize_t len){
  if(!m_is_open)
    return -1;
  if(len > 4096 || len <=0)
    return -1;
  if(m_ostringstream.str().empty())
    return 0;
  unsigned int retlen;
  if(m_ostringstream.str().size() < len){
    memcpy(buf, m_ostringstream.str().c_str(), m_ostringstream.str().size());
    retlen = m_ostringstream.str().size();
  }
  else{
    memcpy(buf, m_ostringstream.str().c_str(), len);
    retlen = len;
  }
  //Lets not get complicated, and just clear.
  m_ostringstream.str(std::string());
  return retlen;
  
}
